package com.million.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.million.eduservice.client.VodClient;
import com.million.eduservice.entity.EduVideo;
import com.million.eduservice.entity.vo.video.VideoInfoFormVo;
import com.million.eduservice.mapper.EduVideoMapper;
import com.million.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.million.servicebase.exception.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author 十麓
 * @since 2022-03-24
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private VodClient vodClient;

    //添加小节信息
    @Override
    public void addVideoInfo (VideoInfoFormVo videoInfoFormVo) {
        EduVideo eduVideo = new EduVideo();
        BeanUtils.copyProperties(videoInfoFormVo, eduVideo);
        //添加到数据库中
        int insert = baseMapper.insert(eduVideo);
        if (insert == 0) {
            throw new GuliException(20001, "添加失败");
        }
    }

    //根据小节id查询小节信息
    @Override
    public VideoInfoFormVo getVideoInfo (String videoId) {
        VideoInfoFormVo videoInfoFormVo = new VideoInfoFormVo();
        EduVideo eduVideo = baseMapper.selectById(videoId);
        if (eduVideo != null) {
            BeanUtils.copyProperties(eduVideo, videoInfoFormVo);
        }
        return videoInfoFormVo;
    }

    //修改小节信息
    @Override
    public void updateVideoInfo (VideoInfoFormVo videoInfoFormVo) {
        EduVideo eduVideo = new EduVideo();
        BeanUtils.copyProperties(videoInfoFormVo, eduVideo);
        int update = baseMapper.updateById(eduVideo);
        if (update == 0) {
            throw new GuliException(20001, "修改小节信息失败");
        }
    }

    //删除小节信息 根据课程id
    //TODO 删除小节的时候需要删除对应的视频
    @Override
    @Transactional  //添加事务
    public void removeVideoById (String courseId) {
        //根据课程id  获取所有的小节中的视频id
        List<String> sourceIdList = baseMapper.videoSourceIdList(courseId);
        //存放不为空的视频id
        List<String> videoSourceIdList = new ArrayList<>();
        for (String videoSourceId : sourceIdList) {
            //如果视频id不为空，就加进去
            if(!StringUtils.isEmpty(videoSourceId)){
                videoSourceIdList.add(videoSourceId);
            }
        }
        if(videoSourceIdList.size() > 0){
            vodClient.removeAllVod(videoSourceIdList);
        }

        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",courseId);
        baseMapper.delete(queryWrapper);
    }

}
